import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export function requestHandler (config, tokenField) {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers[tokenField] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (config.url.indexOf('upload') < 0 && config.url.indexOf('import') < 0) {
      config.headers['content-Type'] = 'application/json'
      config.data = JSON.stringify(config.data)
    }
  }
  return config
}

export function responseHandler (response) {
  // 统一处理后台错误
  if (!response.data.success) {
    message.error('请求失败！' + response.data.msg)
  }
  return response.data
}

export function errorHandler (error) {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

const defaultOptions = {
  tokenField: 'Access-Token',
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 5000 // 请求超时时间
}

export function createAxios ({ baseURL, tokenField, timeout } = defaultOptions) {
  // 创建 axios 实例
  const service = axios.create({ baseURL, timeout })
  service.interceptors.request.use(config => requestHandler(config, tokenField), errorHandler)
  service.interceptors.response.use(responseHandler, errorHandler)
  return service
}
